# Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import pickle
from utils import get_logger


class BaseClassificationHead:
    def __init__(self, label_name, head_params=None):
        self.label_name = label_name
        self.head_params = head_params if head_params else {}
        assert isinstance(self.head_params, dict)
        self.logger = get_logger(self.__class__.__name__)

        self.model = None
        self.model_name = f"{self.__class__.__name__}_{self.label_name}"

    def train(self, datasets):
        raise NotImplementedError()

    def infer(self, datasets):
        raise NotImplementedError()

    def export(self, export_dir):
        if not os.path.exists(export_dir):
            os.makedirs(export_dir, exist_ok=True)
        export_path = os.path.join(export_dir, f"{self.model_name}.pkl")
        if os.path.exists(export_path):
            self.logger.warning(f"model {export_path} already exists, overwrite")
        if self.model:
            try:
                with open(export_path, "wb") as f:
                    pickle.dump(self.model, f)
                self.logger.info(f"export model {self.model_name} successfully")
            except Exception as e:
                self.logger.error(f"export model {self.model_name} failed, error: {e}")
        else:
            self.logger.warning("No trained model found to export.")

    def load(self, model_dir):
        model_path = os.path.join(model_dir, f"{self.model_name}.pkl")
        assert os.path.exists(model_path), f"model {model_path} not exists"
        with open(model_path, "rb") as f:
            self.model = pickle.load(f)
        self.logger.info(f"load model {self.model_name} successfully")
